package com.xu.mall.framework.dao;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.RowBounds;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import com.xu.mall.framework.model.Pager;
import com.xu.mall.framework.model.PageContext;
import com.xu.mall.framework.util.GenericsUtils;

public class BaseDao<T extends Serializable> extends SqlSessionDaoSupport implements IBaseDao<T> {
	protected static final Log log = LogFactory.getLog(BaseDao.class);

	@SuppressWarnings("unchecked")
	protected Class<T> entityClass = GenericsUtils.getSuperClassGenricType(this.getClass());

	/**
	 * 新增对象
	 * 
	 * @param obj
	 * @return
	 */
	public int add(T obj) {
		return getSqlSession().insert(entityClass.getName() + SUFFIX_INSERT, obj);
	}

	/**
	 * 删除对象
	 * 
	 * @param obj
	 * @return
	 */
	public int delete(Serializable id) {
		return getSqlSession().delete(entityClass.getName() + SUFFIX_DELETE_BY_ID, id);
	}

	/**
	 * 更新对象
	 * 
	 * @param obj
	 * @return
	 */
	public int update(T obj) {
		return getSqlSession().update(entityClass.getName() + SUFFIX_UPDATE, obj);
	}

	/**
	 * 根据ID获取对象
	 * 
	 * @param clz
	 * @param id
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public T get(Serializable id) {
		return (T) getSqlSession().selectOne(entityClass.getName() + SUFFIX_GET_BY_ID, id);
	}

	/**
	 * 分页查询
	 * 
	 * @param params
	 * @return
	 */
	public Pager<T> find(Map<String, Object> params) {
		return this.find(entityClass.getName() + SUFFIX_FIND, params);
	}

	/**
	 * 分页查询，通过sqlId
	 * 
	 * @param sqlId
	 * @param params
	 * @return
	 */
	public Pager<T> find(String sqlId, Map<String, Object> params) {
		return find(sqlId, params, PageContext.getStartIndex(), PageContext.getPageSize());
	}

	/**
	 * 分页查询，通过sqlId
	 * 
	 * @param sqlId
	 * @param params
	 * @param startIndex
	 * @param pageSize
	 * @return
	 */
	public Pager<T> find(String sqlId, Map<String, Object> params, int startIndex, int pageSize) {
		pageSize = pageSize == 0 ? 20 : pageSize;
		if (params == null) {
			params = new HashMap<String, Object>();
		}
		params.put("sortField", PageContext.getSortField());
		params.put("sortType", PageContext.getSortType());

		List<T> result = getSqlSession().selectList(sqlId, params, new RowBounds(startIndex, pageSize));
		int totalRecord = getSqlSession().selectOne(sqlId + SUFFIX_COUNT, params);

		Pager<T> pager = new Pager<T>();
		pager.setResult(result);
		pager.setTotalRecord(totalRecord);
		pager.setStartIndex(startIndex);
		pager.setPageSize(pageSize);

		return pager;
	}
}
